// MainView.java
package exercise.jslide.jslide.view;

import exercise.jslide.jslide.controller.ImageController;
import exercise.jslide.jslide.controller.TextController;
import exercise.jslide.jslide.model.shapes.Circle;
import exercise.jslide.jslide.model.shapes.Ellipse;
import exercise.jslide.jslide.model.shapes.Line;
import exercise.jslide.jslide.model.shapes.Rectangle;
import exercise.jslide.jslide.model.text.TextBox;
import exercise.jslide.jslide.model.text.TextStyle;
import exercise.jslide.jslide.utils.SerializableColor;
import exercise.jslide.jslide.utils.SerializableFont;
import exercise.jslide.jslide.view.dialog.ColorPickerDialog;
import exercise.jslide.jslide.view.dialog.FontDialog;
import exercise.jslide.jslide.view.dialog.TextStyleDialog;
import exercise.jslide.jslide.view.tools.SelectTool;
import exercise.jslide.jslide.view.tools.ShapeTool;
import exercise.jslide.jslide.view.tools.TextTool;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import exercise.jslide.jslide.view.components.*;
import exercise.jslide.jslide.view.ribbon.*;
import exercise.jslide.jslide.controller.PresentationController;
import exercise.jslide.jslide.app.AppContext;

/**
 * <p>该类是应用程序的主视图类，用于显示应用程序的主界面。</p>
 * <p>该类继承自 BorderPane 类，表示一个具有上、下、左、右和中五个区域的面板。</p>
 *
 * 该类包含了应用程序的所有视图组件，
 * <ul>
 *     <li>Ribbon工具栏（ribbonBar）</li>
 *     <li>幻灯片导航器（slideNavigator）</li>
 *     <li>编辑器视图（editorView）</li>
 *     <li>状态栏（statusBar）</li>
 *     <li>应用程序的所有控制器，如PresentationController、ImageController和TextController</li>
 *
 * </ul>
 */
public class MainView extends BorderPane {
    private AppContext appContext;
    private RibbonBar ribbonBar;
    private SlideNavigator slideNavigator;
    private EditorView editorView;
    private StatusBar statusBar;
    private PresentationController presentationController;
    private ImageController imageController;
    private TextController textController;

    /**
     * 该构造方法用于初始化 MainView 类的实例，
     * 同时初始化应用程序的上下文对象 appContext、
     * PresentationController、ImageController、TextController、
     * RibbonBar、EditorView、StatusBar和SlideNavigator。
     */
    public MainView() {
        appContext = AppContext.getInstance();

        // 创建控制器
        presentationController = new PresentationController(appContext.getCurrentPresentation(), this);
        imageController = new ImageController(this);
        initializeComponents();
        layoutComponents();
//        setupEventHandlers();
        textController = new TextController(editorView);
        appContext.setMainView(this);
    }

    private void initializeComponents() {

        // 创建Ribbon工具栏
        ribbonBar = createRibbonBar();

        ribbonBar.selectTab(1);

        // 创建编辑器视图
        editorView = new EditorView();

        // 创建状态栏
        statusBar = new StatusBar();

        // 创建幻灯片导航器
        slideNavigator = new SlideNavigator(this);


    }


    private RibbonBar createRibbonBar() {
        RibbonBar ribbonBar = new RibbonBar();

        // 文件选项卡
        RibbonTab fileTab = new RibbonTab("文件");

        // 文件组
        RibbonGroup fileGroup = new RibbonGroup("文件操作");
        fileGroup.addAll(
                createFileButton("新建", "new", e -> presentationController.newPresentation()),
                createFileButton("打开", "open", e -> presentationController.openPresentation()),
                createFileButton("保存", "save", e -> presentationController.savePresentation()),
                createFileButton("另存为", "save-as", e -> presentationController.saveAsPresentation())
        );

        fileTab.addGroup(fileGroup);

        // 开始选项卡
        RibbonTab homeTab = new RibbonTab("开始");

        // 剪贴板组
        RibbonGroup clipboardGroup = new RibbonGroup("剪贴板");
        clipboardGroup.addAll(
                createFileButton("删除", "delete", e -> editorView.deleteSelectedElement()),
                createFileButton("复制", "copy", e -> editorView.copy()),
                createFileButton("剪切", "cut", e -> editorView.cut()),
                createFileButton("粘贴", "paste", e -> editorView.paste())
        );


        // 幻灯片组
        RibbonGroup slidesGroup = new RibbonGroup("幻灯片");
        RibbonButton newSlideButton = new RibbonButton("新建幻灯片", "new-slide");
        newSlideButton.setOnAction(e -> appContext.getCurrentPresentation().createNewSlide(this));
//        RibbonButton layoutButton = new RibbonButton("布局", "layout");
//        layoutButton.setOnAction(e -> presentationController.changeLayout());
//        RibbonButton resetButton = new RibbonButton("重置", "reset");
//        resetButton.setOnAction(e -> presentationController.resetSlide());

        slidesGroup.addAll(newSlideButton);

//        // 字体组
//        RibbonGroup fontGroup = new RibbonGroup("字体");
//        ComboBox<String> fontFamilyBox = new ComboBox<>();
//        fontFamilyBox.getItems().addAll("宋体", "黑体", "Arial", "Times New Roman");
//        ComboBox<Integer> fontSizeBox = new ComboBox<>();
//        fontSizeBox.getItems().addAll(8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72);
//
//        HBox fontControls = new HBox(5);
//        fontControls.getChildren().addAll(fontFamilyBox, fontSizeBox);
//
//        HBox fontStyles = new HBox(2);
//        fontStyles.getChildren().addAll(
//                new RibbonToggleButton("粗体", "bold"),
//                new RibbonToggleButton("斜体", "italic"),
//                new RibbonToggleButton("下划线", "underline")
//        );
//
//        fontGroup.addAll(fontControls, fontStyles);

        // 撤销重做组
        RibbonGroup undoRedoGroup = new RibbonGroup("撤销/重做");
        RibbonButton undoButton = new RibbonButton("撤销", "undo");
        undoButton.setOnAction(e -> appContext.applyUndo());
        RibbonButton redoButton = new RibbonButton("重做", "redo");
        redoButton.setOnAction(e -> appContext.applyRedo());
        undoRedoGroup.addAll(undoButton, redoButton);

        // 添加所有组到主选项卡
        homeTab.addGroups(clipboardGroup, slidesGroup, undoRedoGroup);

        // 插入选项卡
        RibbonTab insertTab = new RibbonTab("插入");

        // 绘图组
        RibbonGroup drawingGroup = new RibbonGroup("形状");

        // 创建形状按钮并添加事件处理
        RibbonButton rectangleBtn = new RibbonButton("矩形", "rectangle");
        rectangleBtn.setOnAction(e -> {
            editorView.setCurrentTool(new ShapeTool(editorView, Rectangle.class));
        });

        RibbonButton circleBtn = new RibbonButton("正圆", "circle");
        circleBtn.setOnAction(e -> {
            editorView.setCurrentTool(new ShapeTool(editorView, Circle.class));
        });

        RibbonButton ellipseBtn = new RibbonButton("椭圆", "ellipse");
        ellipseBtn.setOnAction(e -> {
            editorView.setCurrentTool(new ShapeTool(editorView, Ellipse.class));
        });

        RibbonButton lineBtn = new RibbonButton("直线", "line");
        lineBtn.setOnAction(e -> {
            editorView.setCurrentTool(new ShapeTool(editorView, Line.class));
        });

        drawingGroup.addAll(rectangleBtn, ellipseBtn, lineBtn, circleBtn);

        //文本框组
        RibbonGroup textBoxGroup = new RibbonGroup("文本框");
        RibbonButton textBoxBtn = new RibbonButton("文本框", "text-box");
        textBoxBtn.setOnAction(e -> {
            editorView.setCurrentTool(new TextTool(editorView));
        });
        textBoxGroup.addAll(textBoxBtn);


        // 添加插入选项卡的组
        RibbonGroup mediaGroup = new RibbonGroup("媒体");
        mediaGroup.addAll(
                createFileButton("图片", "picture", e -> imageController.openImage()),
//                new RibbonButton("图片", "picture"),
                new RibbonButton("视频", "video"),
                new RibbonButton("音频", "audio")
        );
        insertTab.addGroups(drawingGroup, textBoxGroup, mediaGroup);


        // 形状格式选项卡
        RibbonTab shapeFormatTab = new RibbonTab("形状格式");

        // 形状样式组
        RibbonGroup shapeStyleGroup = new RibbonGroup("形状样式");

        // 创建形状样式按钮并添加事件处理
        RibbonButton fillBtn = new RibbonButton("填充颜色", "fill");
        fillBtn.setOnAction(e -> {
            setFillColor();
        });

        RibbonButton lineBtn2 = new RibbonButton("线条颜色", "line");
        lineBtn2.setOnAction(e -> {
            setStrokeColor();
        });

        shapeStyleGroup.addAll(fillBtn, lineBtn2);

        // 添加形状格式选项卡的组
        shapeFormatTab.addGroup(shapeStyleGroup);


        // 文本格式选项卡
        RibbonTab textFormatTab = new RibbonTab("文本格式");

        // 文本样式组
        RibbonGroup textStyleGroup = new RibbonGroup("文本样式");

        // 创建文本样式按钮并添加事件处理
        RibbonButton fontBtn = new RibbonButton("字体", "font");
        fontBtn.setOnAction(e -> {
            setFont();
        });

        RibbonButton colorBtn = new RibbonButton("颜色", "color");
        colorBtn.setOnAction(e -> {
            setColor();
        });

        //文本风格设置
        RibbonButton textStyleBtn = new RibbonButton("文本风格", "text-style");
        textStyleBtn.setOnAction(e -> {
            setTextStyle();
        });

        textStyleGroup.addAll(fontBtn, colorBtn, textStyleBtn);

        // 添加文本格式选项卡的组
        textFormatTab.addGroup(textStyleGroup);



        // 添加所有选项卡到Ribbon
        ribbonBar.getTabs().addAll(fileTab, homeTab, insertTab, shapeFormatTab, textFormatTab);

        return ribbonBar;
    }

    private void setTextStyle() {
        TextStyleDialog textStyleDialog = new TextStyleDialog(appContext.getPrimaryStage());
        textStyleDialog.show();
        TextStyle textStyle = textStyleDialog.getTextStyle();
        if (textStyle != null) {
            if (editorView.getCurrentTool() != null && editorView.getCurrentTool().getClass() == SelectTool.class) {
                SelectTool selectTool = (SelectTool) editorView.getCurrentTool();
                if (selectTool.getSelectedElement().getClass() == TextBox.class) {
                    TextBox textBox = (TextBox) selectTool.getSelectedElement();
                    textBox.setTextStyle(textStyle);
                    editorView.redraw();
                }
            }
        }
    }

    private void setColor() {
        ColorPickerDialog colorPickerDialog = new ColorPickerDialog(appContext.getPrimaryStage());
        colorPickerDialog.show();
        SerializableColor color = colorPickerDialog.getColor();
        if (color != null) {
            if (editorView.getCurrentTool() != null && editorView.getCurrentTool().getClass() == SelectTool.class) {
                SelectTool selectTool = (SelectTool) editorView.getCurrentTool();
                if(selectTool.getSelectedElement().getClass() == TextBox.class){
                    TextBox textBox = (TextBox) selectTool.getSelectedElement();
                    textBox.setTextColor(color.getFXColor());
                    editorView.redraw();
                }
            }
        }
    }

    private void setFont() {
        FontDialog fontDialog = new FontDialog(appContext.getPrimaryStage());
        fontDialog.show();
        SerializableFont fontName = fontDialog.getSelectedFont();
        if (fontName != null) {
            if (editorView.getCurrentTool() != null && editorView.getCurrentTool().getClass() == SelectTool.class) {
                SelectTool selectTool = (SelectTool) editorView.getCurrentTool();
                if(selectTool.getSelectedElement().getClass() == TextBox.class){
                    TextBox textBox = (TextBox) selectTool.getSelectedElement();
                    textBox.setFont(fontName);
                    editorView.redraw();
                }
            }
        }

    }

    private void setStrokeColor() {
        ColorPickerDialog colorPickerDialog = new ColorPickerDialog(appContext.getPrimaryStage());
        colorPickerDialog.show();
        SerializableColor color = colorPickerDialog.getColor();
        if (color != null) {
            if (editorView.getCurrentTool() != null && editorView.getCurrentTool().getClass() == SelectTool.class) {
                SelectTool selectTool = (SelectTool) editorView.getCurrentTool();
                selectTool.getSelectedElement().setStrokeColor(color);
                editorView.redraw();
            }
        }
    }

    private void setFillColor() {
        ColorPickerDialog colorPickerDialog = new ColorPickerDialog(appContext.getPrimaryStage());
        colorPickerDialog.show();
        SerializableColor color = colorPickerDialog.getColor();
        if (color != null) {
            if (editorView.getCurrentTool() != null && editorView.getCurrentTool().getClass() == SelectTool.class) {
                SelectTool selectTool = (SelectTool) editorView.getCurrentTool();
                selectTool.getSelectedElement().setFillColor(color);
                editorView.redraw();
            }
        }
    }

    private void layoutComponents() {
        // 设置顶部区域
        VBox topContainer = new VBox();
        topContainer.getChildren().addAll(ribbonBar);
        setTop(topContainer);

        //设置底部区域
        VBox bottomContainer = new VBox();
        bottomContainer.getChildren().addAll(statusBar);
        setBottom(bottomContainer);

        //设置中央区域
//        VBox centerContainer = new VBox();

        // 设置左侧幻灯片导航器
        VBox leftContainer = new VBox();
        VBox.setVgrow(slideNavigator, Priority.ALWAYS);
//        leftContainer.setPrefWidth(200);
        leftContainer.getChildren().add(slideNavigator);
        VBox.setVgrow(leftContainer, Priority.ALWAYS);

        leftContainer.setMinWidth(200);
        leftContainer.setMaxWidth(200);

        VBox rightContainer = new VBox();
        VBox.setVgrow(editorView, Priority.ALWAYS);
        rightContainer.getChildren().add(editorView);
        VBox.setVgrow(rightContainer, Priority.ALWAYS);

        // 设置分隔符
        SplitPane splitPane = new SplitPane();
        splitPane.setOrientation(Orientation.HORIZONTAL);
        splitPane.getItems().addAll(leftContainer, rightContainer);
        splitPane.setDividerPositions(0.2);



        setCenter(splitPane);
    }

    private RibbonButton createFileButton(String text, String iconName, EventHandler<ActionEvent> handler) {
        RibbonButton button = new RibbonButton(text, iconName);
        button.setOnAction(handler);
        return button;
    }

    public void updateView() {
        slideNavigator.updateSlideList();
        statusBar.updateSlideNumber(appContext.getCurrentPresentation().getCurrentSlideIndex() + 1,
                appContext.getCurrentPresentation().getSlides().size());
        editorView.redraw();
    }


    // Getter方法
    public EditorView getEditorView() {
        return editorView;
    }

    public SlideNavigator getSlideNavigator() {
        return slideNavigator;
    }

    public StatusBar getStatusBar() {
        return statusBar;
    }

    //设置Ribbon切换到指定选项卡
    public void selectRibbonTab(int index) {
        ribbonBar.selectTab(index);
    }
}